import { createRouter, createWebHashHistory } from 'vue-router'
import {getRouters} from '@/api/index.ts'
import type {INavMenu} from '@/api/types.ts'
import {menuStore} from '@/stores/users.ts'
import { getToken } from '@/api/auth'
const routes  = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/home',
    component: ()=> import('../views/Home.vue'),
  
  },
  {
    path: '/index',
    component: ()=> import('../views/Index.vue'),

  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
}
)
//路由守卫
router.beforeEach(async(to, from, next) => {
   if(to.path==='/login'){
    if (getToken()){
      return next('/home')
    } 
    return next();//继续跳转，不阻塞路由
   }
   if (!getToken()) {
    return next('/login')
   }
    if(menuStore() &&  menuStore().navMenu.length===0){
      let {data}=await getRouters();
      menuStore().setNavMenu(data.data);
      //转换数据类型
     // const newRoutes=addNewRoutes(data.data);
      addDynamicRoutes(data.data)
      //router.addRoute(newRoutes);//添加路由配置
      next();//继续跳转，不阻塞路由
    }else{
      next();
    }
  
});


/*function addNewRoutes(data:INavMenu[]): {
  let HomeRoutes=routes.filter(v => v.path==='/home')[0];
  HomeRoutes.children=[];
  data.forEach((item:INavMenu) => {
    HomeRoutes.children?.push({
     path: item.path,
      name: item.name,
      component: () => import(`@/views${item.path}/index.vue`),
      meta: item.meta,
      children: item.children || []
    })
  });
  return HomeRoutes;
}*/


const addDynamicRoutes = (routes: INavMenu[]) => {
  routes.forEach(route => {
  console.log("route.path::::"+route.path)
 let modules = import.meta.glob('../views/**/index.vue')
    router.addRoute({
      path: route.path,
      name: route.name,
     // component: () => import(`../views${route.path}/index.vue`),
      component: modules[`../views${route.path}/index.vue`],
      meta: route.meta,
      children: route.children || []
    })
  })
}

export default router
